import {
  login,
  logout,
  getInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'

const getDefaultState = () => {
  return {
    userInfo: {},
    token: getToken(),
    name: '',
    avatar: 'https://ftp.bmp.ovh/imgs/2021/06/8fe55c96663e5e4b.png' //  蚂蚁
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token) //  将token存储到本地缓存  本地缓存使用的是 js-cookie
  },
  // 删除缓存
  removeToken(state) {
    state.token = null // 删除vuex的token
    removeToken() // 先清除 vuex  再清除缓存 vuex和 缓存数据的同步
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    console.log(avatar, 5555)
    state.avatar = avatar
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // ajaxHandle(context,form){
  // 	context.commit('SET_TOKEN',form)

  // },

  // ajaxHandle2({commit},form){
  // 	commit('SET_TOKEN',form)

  // },

  // user login
  login({
    commit
  }, userInfo) {
    const {
      mobile,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        mobile: mobile.trim(),
        password: password
      }).then(response => {
        console.log(response, 666777)

        commit('SET_TOKEN', response) //  将token存到store中
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({
    commit
  }) {
    return new Promise((resolve, reject) => {
      getInfo().then(data => {
        console.log(data, 4567)

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const {
          username
        } = data
        commit('SET_NAME', username)
        commit('SET_USERINFO', data)
        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('permission/SET_ROUTES', [], {
        root: true
      }) //  初始化权限
      commit('RESET_STATE')
      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
